package au.com.evoCoach.controller;

import java.util.Map;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import au.com.evoCoach.domain.Coach;
import au.com.evoCoach.form.ChangePasswordForm;
import au.com.evoCoach.service.CoachService;

@Controller
public class ChangePassword {
	private CoachService coachService;
	
	private ChangePassword() {}
	
	@Autowired
	public ChangePassword(CoachService coachService) {
		this.coachService = coachService;
	}
	
	@RequestMapping("/submitChangePassword.action")
	public String submitChangePassword(ChangePasswordForm changePasswordForm, HttpSession session, Map model) {
		
	    Coach coach = (Coach) session.getAttribute("loggedInCoach");
	    
	    if (!coach.getPassword().equals(changePasswordForm.getOldPassword())) {
			model.put("changePasswordError", Boolean.TRUE);
			
			return "changePassword";
		}
	    
	    coach.setPassword(changePasswordForm.getNewPassword());
	    coachService.updateCoach(coach);
	    
		model.put("changePasswordSuccess", Boolean.TRUE);
		
		return "redirect:displayHomePage.action";
	}
	
	@RequestMapping("/displayChangePassword.action")
	public String displayChangePassword(Map model) {
		
		model.put("changePasswordForm", new ChangePasswordForm());
		
		return "changePassword";
	}	
	
}
